package com.copy.scan.other;

import com.copy.mark.EasyCopy;
import com.copy.scan.ScanBasePackageStrategy;

import java.io.File;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class ScanBasePackageByOtherHandler implements ScanBasePackageStrategy {


    @Override
    public Set<Class<?>> scannerPackages(String basePackage) {
        Set<Class<?>> classes = new HashSet<>();
        scan(classes,basePackage);
        return classes;
    }
    public void scan(Set<Class<?>> classes,String basePackage){
        //扫描编译好的类路径下所有的类
        URL url = this.getClass().getClassLoader().getResource("./" + basePackage.replaceAll("\\.", "/"));
        String fileStr = url.getFile();

        File file = new File(fileStr);
        //拿到所有类com.enjoy下的james文件夹
        String[] filesStr = file.list();

        for (String path : filesStr) {
            File filePath = new File(fileStr+ "/"+ path);//扫描com.enjoy.james下的所有class类
            boolean directory = filePath.isDirectory();
            //递归调用扫描,如果是路径,继续扫描
            if (filePath.isDirectory()) {
                // com.enjoy.james
                scan(classes,basePackage + "." + path);
            } else {
                String className = basePackage + "." + filePath.getName();
                className = className.replace(".class", "");
                try {
                    Class<?> cls = Class.forName(className);
                    if (cls.isAnnotationPresent(EasyCopy.class))
                    classes.add(cls);//如果是class文件则加入List集合(待生成bean)
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
